package com.mengfou.tasks;

import com.android.build.gradle.AppExtension;
import com.android.build.gradle.api.ApplicationVariant;

import org.gradle.api.DefaultTask;
import org.gradle.api.Project;
import org.gradle.api.tasks.TaskAction;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 梦否 on 2023/1/1
 * @blog https://mengfou.blog.csdn.net/
 */
public class ApkVersionTask extends DefaultTask {
    private Project mProject;
    private String mVariant;

    @TaskAction
    public void modifyFileName() {
        AppExtension appExtension = mProject.getExtensions().getByType(AppExtension.class);
        for (ApplicationVariant applicationVariant : appExtension.getApplicationVariants()) {
            if(mVariant.equals(applicationVariant.getName())) {
                try {
                    String stringBuilder = mProject.getBuildDir().getAbsolutePath() +
                            File.separator +
                            "outputs" +
                            File.separator +
                            "apk" +
                            File.separator +
                            applicationVariant.getBuildType().getName();
                    File parent = new File(stringBuilder);
                    for (File file : Objects.requireNonNull(parent.listFiles())) {
                        if (file.getName().endsWith(".apk")) {
                            File outputNewFile = new File(parent, "mengfou-" + getConfigVersion() + "-" + mVariant.toLowerCase() + ".apk");
                            file.renameTo(outputNewFile);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String getConfigVersion() {
        try {
            File file = new File(mProject.getBuildFile().getParent(), "versions.properties");
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int len = -1;
            StringBuilder stringBuffer = new StringBuilder();
            while((len = fileInputStream.read(buffer)) != -1) {
                stringBuffer.append(new String(buffer, 0, len));
            }
            if(stringBuffer.toString().trim().length() != 0) {
                String[] split = stringBuffer.toString().split("=");
                if(split.length == 2 && split[0].equals("apk-version")) {
                    return split[1];
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "empty";
    }

    public void setProject(Project project) {
        mProject = project;
    }

    public void setVariant(String variant) {
        mVariant = variant;
    }
}
